package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUEST_COUNT = 3;
    private static final int MAX_PEQUEST_WINDOW_SIZE =  60;

    //计数
    private final ConcurrentHashMap<String,Integer>clientCounts
            = new ConcurrentHashMap<>();
    //记录访问时间
    private final ConcurrentHashMap<String, LocalDateTime>lastResetTimes
            =new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        log.debug("进入到网站限流的拦截器");
        String clientIp = request.getRemoteAddr();
        LocalDateTime lastTime = lastResetTimes.get(clientIp);
        if (lastTime == null || LocalDateTime.now()
                .isAfter(lastTime.plusSeconds(MAX_PEQUEST_WINDOW_SIZE))) {
            clientCounts.put(clientIp, 0);
            lastResetTimes.put(clientIp, LocalDateTime.now());
        }
            Integer i = clientCounts.get(clientIp);
            i = i + 1;
            clientCounts.put(clientIp, i);
            if (i > MAX_REQUEST_COUNT) {
                throw new RuntimeException("访问次数超出限制");
            }
            return true;
        }
    }
